package com.qianbei.view.binding;

import android.content.Context;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetBindBean;
import com.qianbei.bean.GetBindBean1;
import com.qianbei.bean.GetBindBean2;
import com.qianbei.bean.GetBoxBody;
import com.qianbei.bean.GetBoxBody1;
import com.qianbei.bean.GetEmpty_Body;
import com.qianbei.bean.GetUpbox;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.user.login.Login_regist_topFragment;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RequestPersistent;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.UHFManager;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by gaoml on 2018/1/22.
 */

public class UnBingActivity extends BaseActivity {


    @Bind(R.id.bing_num)
    EditText bingNum;
    @Bind(R.id.bing_frd)
    TextView bingFrd;
    @Bind(R.id.taction_save)
    TextView tactionSave;
    @Bind(R.id.view_num)
    RelativeLayout viewNum;
    @Bind(R.id.view_frid)
    RelativeLayout viewFrid;
    private Login_regist_topFragment title;

    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;
    private IUHFService iuhfService;

    int type;
    /**
     * 1 按RFID 解绑   0：按箱子编号解绑
     */
    int select = 0;

    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);
    /**
     * 成功上电
     */
    private AtomicBoolean isOpenSucces = new AtomicBoolean(false);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("gml", "start-----------onCreate");
        setContentView(R.layout.gufei_unbing_acitivty);
        title = (Login_regist_topFragment) getSupportFragmentManager().findFragmentById(R.id.regist_login);

//        if(true){
//            title.setUnSelcet();
////            showFragment(mLoginFragment,  R.id.lr_container);
//        }else {
//            title.setSelcet();
////            showFragment(mRegistFragment,  R.id.lr_container);
//        }
        ButterKnife.bind(this);
        setTitle("周转箱解绑定");
        mTitle.setrightTitle("扫描");
        iuhfService = MyApplication.iuhfService;
//                    UHFManager.getUHFService(UnBingActivity.this);

        if (iuhfService != null) {

            iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
                @Override
                public void getInventoryData(SpdInventoryData var1) {

                    handler.sendMessage(handler.obtainMessage(111, var1));

                }
            });
        }
        newWakeLock();
        Log.d("gml", "end-----------onCreate");
    }

    boolean ishow = false;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    Log.d("gaoaa", var1.epc);
                    if (!TextUtils.isEmpty(var1.epc)) {
                        ring();
                        if (bingFrd != null) {
                            bingFrd.setText(var1.epc);
                            iuhfService.newInventoryStop();
                            mTitle.setrightTitle("扫描");
                            handler.removeCallbacksAndMessages(null);
                        }

                    }
                    break;
            }
        }
    };

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }


    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        Log.d("gml", "start-----------openDev");
        if (iuhfService.OpenDev() != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        Log.d("gml", "end-----------openDev");
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
                //断电后选卡操作会失效，需要重新选卡（掩码）
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                mTitle.setrightTitle("正在扫描");
                //重复点扫描按钮时 只做一次上电操作
                if (isOpenDev.get() == false) {
                    isOpenDev.set(true);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            try {
                                if (openDev()) {
                                    isOpenDev.set(false);
                                    return null;
                                } else {
                                    isOpenSucces.set(true);
                                }
                                iuhfService.set_antenna_power(MyApplication.setValue);
                            } catch (Exception e) {
                                e.printStackTrace();
                                isOpenDev.set(false);
                                return null;
                            }
                            iuhfService.newInventoryStart();
                            return null;
                        }
                    }.execute();

                } else if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStart();
                }
                break;

            case R.id.shop_button:
                select = 1;
                viewNum.setVisibility(View.GONE);
                viewFrid.setVisibility(View.VISIBLE);

//                showFragment(mRegistFragment,  R.id.lr_container);
                break;
            case R.id.food_button:
                select = 0;
                viewNum.setVisibility(View.VISIBLE);
                viewFrid.setVisibility(View.GONE);
//                showFragment(mLoginFragment,  R.id.lr_container);
                break;
            default:
                break;
        }
    }


    @OnClick({R.id.taction_save, R.id.bing_frd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.taction_save: {
                Log.d("UnBindType", select + "");
                if (select == 0) {//解绑箱子
                    if (TextUtils.isEmpty(bingNum.getText().toString())) {
                        new MsgAlert().show("请输入箱号");
                    } else {


                        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                                .setMessage("是否确认解绑定？")//设置对话框的内容
                                //设置对话框的按钮
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        unbindBoxByNumber(bingNum.getText().toString());
                                        dialog.dismiss();
                                    }
                                }).create();
                        dialog.show();

                    }
                } else if (select == 1) {

                    if (TextUtils.isEmpty(bingFrd.getText().toString())) {
                        new MsgAlert().show("请扫描FIRD");
                    } else {


                        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                                .setMessage("是否确认解绑定？")//设置对话框的内容
                                //设置对话框的按钮
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        unbindFidByNumber(bingFrd.getText().toString());
                                        dialog.dismiss();
                                    }
                                }).create();
                        dialog.show();

                    }


                }

                break;
            }

            case R.id.bing_frd: {
                findViewById(R.id.tv_right).callOnClick();
                break;
            }
        }
    }


    /**
     * 按箱号解绑
     */
    private void unbindBoxByNumber(String boxNo) {


        RequeastBean bean = new RequeastBean("unbindBoxByNumber", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                new GetBindBean(boxNo));
        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean); bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetBindBean.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            //finish();
        } else {

            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("解绑成功");
                        bingNum.setText("");
                        //finish();
                    }

                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }


    }

    private void ring() {


        Uri notification = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.beep_once);
        if (notification == null) return;
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }

    /**
     * 按RFID解绑
     */
    private void unbindFidByNumber(String rfidTxt) {
        ArrayList<String> rfid = new ArrayList<>();
        rfid.add(rfidTxt);


        RequeastBean bean = new RequeastBean("updateLoad", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                new GetBindBean1(new GetBindBean2(rfid)));
        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean); bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetBindBean1.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            handler.removeCallbacksAndMessages(null);
            iuhfService.newInventoryStop();
            //finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("解绑成功");
                        bingFrd.setText("");
                        handler.removeCallbacksAndMessages(null);
                        iuhfService.newInventoryStop();
                        //finish();
                    }

                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }


    }
}
